package actions.generate.dialog;

import actions.generate.BindViewBeans;
import com.intellij.openapi.ui.VerticalFlowLayout;
import utils.CommonUtil;

import javax.swing.*;
import java.util.LinkedList;
import java.util.List;

public class IDSelectDialog extends JDialog {
    private final IOnConfirm onConfirmListener;
    private final List<BindViewBeans.BindModel> models;

    public static void show(IOnConfirm onConfirmListener, List<BindViewBeans.BindModel> models) {
        IDSelectDialog dialog = new IDSelectDialog(onConfirmListener, models);
        dialog.setLayout(new VerticalFlowLayout());
        CommonUtil.showDialog(dialog, "请选择要生成的id");
    }

    public IDSelectDialog(IOnConfirm onConfirmListener, List<BindViewBeans.BindModel> models) {
        this.onConfirmListener = onConfirmListener;
        this.models = models;
        generateView();
    }

    private void generateView() {
        List<ViewModel> radioButtons = new LinkedList<>();
        for (BindViewBeans.BindModel model : models) {
            JPanel container = new JPanel();
            JCheckBox checkBox = new JCheckBox(model.getId());
            checkBox.setSelected(true);
            container.add(checkBox);

            JLabel label = new JLabel(model.getType());
            container.add(label);

            JTextField textField = new JTextField(model.getPropertyName());
            container.add(textField);

            add(container);
            radioButtons.add(new ViewModel(checkBox, label, textField, model));
        }

        JButton confirmButton = new JButton("确定");
        confirmButton.addActionListener(e -> {
            if (onConfirmListener == null) {
                return;
            }
            models.clear();
            for (ViewModel model : radioButtons) {
                if (model.checkBox.isSelected()) {
                    model.model.setPropertyName(model.textField.getText());
                    models.add(model.model);
                }
            }
            dispose();
            onConfirmListener.onConfirm(models);
        });
        add(confirmButton);
    }

    private static class ViewModel {
        JCheckBox checkBox;
        JLabel label;
        JTextField textField;
        BindViewBeans.BindModel model;

        public ViewModel(JCheckBox checkBox, JLabel label, JTextField textField, BindViewBeans.BindModel model) {
            this.checkBox = checkBox;
            this.label = label;
            this.textField = textField;
            this.model = model;
        }
    }

    public interface IOnConfirm {
        void onConfirm(List<BindViewBeans.BindModel> models);
    }

    public static void main(String[] args) {
    }
}
